﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using YiSha.Enums;
using YiSha.Util.Model;

namespace YiSha.Basics
{
    /// <summary>
    /// 返回值过滤器
    /// </summary>
    public class BasicsResultAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //获取控制器
            var controller = context.Controller as Controller;
            if (controller == null)
            {
                return;
            }
            try
            {
                //模型校验错误信息
                if (context.Result is BadRequestObjectResult)
                {
                    var modelState = context.ModelState;
                    if (!modelState.IsValid)
                    {
                        List<ErrorViewModel> errorList = new List<ErrorViewModel>();
                        //获取错误信息
                        foreach (var key in modelState.Keys)
                        {
                            var state = modelState[key];
                            if (state.Errors.Any())
                            {
                                ErrorViewModel errorView = new ErrorViewModel();
                                errorView.Name = key.ToString();
                                errorView.Msg = state.Errors.First().ErrorMessage;
                                errorList.Add(errorView);
                            }
                        }
                        var msg = string.Join(",", errorList.Select(s => s.Msg).ToList());
                        context.Result = new ObjectResult(new RespResult
                        {
                            MsgCode = MsgCode.Fail,
                            Msg = string.Format("操作失败，错误信息：{0}", msg)
                        });
                    }
                    return;
                }
                //根据实际需求进行具体实现
                if (context.Result is ObjectResult)
                {
                    var objectResult = context.Result as ObjectResult;
                    if (objectResult.StatusCode == 415)
                    {
                        context.Result = new ObjectResult(new RespResult
                        {
                            MsgCode = MsgCode.Fail,
                            Msg = "header类型：content-type 错误，请使用application/json; charset=utf-8"
                        });
                        return;
                    }
                    if (objectResult.Value is ObjectResult)
                    {
                        context.Result = objectResult;
                    }
                    else
                    {
                        if (objectResult.Value is TData<string>)
                        {
                            context.Result = objectResult;
                        }
                        if (objectResult.Value.GetType().IsClass)
                        {
                            context.Result = objectResult;
                        }
                        else
                        {
                            context.Result = new ObjectResult(new
                            {
                                msg = "操作成功",
                                data = objectResult.Value,
                                code = MsgCode.Success
                            });
                        }
                    }
                }
                else if (context.Result is EmptyResult)
                {
                    context.Result = new ObjectResult(new RespResult
                    {
                        MsgCode = MsgCode.DoesNotExist,
                        Msg = "未找到指定资源"
                    });
                }
                else if (context.Result is JsonResult)
                {
                    var result = context.Result as JsonResult;
                    //字符串需要拼接返回格式
                    if (result.Value is string)
                    {
                        context.Result = new ObjectResult(new
                        {
                            msg = result.Value,
                            code = MsgCode.Fail
                        });
                    }
                    else
                    {
                        context.Result = result;
                    }
                }
                //else
                //{
                //    var objectResult = context.Result as ObjectResult;
                //    if (!objectResult.IsEmpty())
                //    {
                //        context.Result = new ObjectResult(objectResult.Value);
                //    }
                //}
                //else if (context.Result is ContentResult)
                //{
                //    context.Result = new ObjectResult(new ResultExecuting { code = 200, msg = "", data = (context.Result as ContentResult).Content });
                //}
                //else if (context.Result is StatusCodeResult)
                //{
                //    context.Result = new ObjectResult(new ResultExecuting { code = (context.Result as StatusCodeResult).StatusCode, msg = "" });
                //}
            }
            catch (Exception ex)
            {
                context.Result = new ObjectResult(new
                {
                    header = new RespResult
                    {
                        MsgCode = MsgCode.ServiceException,
                        Msg = "服务器异常，错误信息：" + ex.Message
                    },
                });
            }
        }
    }
    /// <summary>
    /// 验证错误信息视图模型
    /// </summary>
    public class ErrorViewModel
    {
        /// <summary>
        /// 错误字段名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 错误信息
        /// </summary>
        public string Msg { get; set; }

    }
}
